<template>
  <div>
    <a-alert type="warning" show-icon style="margin-bottom: 18px">
      <template #message>
        管理各云平台的访问密钥，请勿泄漏。可使用接口获取配置密钥，详见
        <a
          href="https://doc.21ds.cn/detail?doc=4731341806141859/4908379888512271"
          target="_blank"
          rel="noopener noreferrer"
          >接口文档</a
        >
      </template>
    </a-alert>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="18">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="平台类型">
              <a-select
                v-model:value="listQuery.platform"
                placeholder="请选择"
                style="width: 180px"
                :options="pltformOption"
              />
            </a-form-item>
            <a-form-item label="搜索项">
              <a-input v-model:value="listQuery.title" placeholder="输入标题/Ak搜索..." />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchSubmit"> 搜索 </a-button>
            </a-form-item>
            <a-form-item>
              <a-button
                v-permission="{ action: 'del_ak_batch' }"
                type="primary"
                danger
                :disabled="selectedRowKeys.length === 0"
                @click="deleteSelect"
              >
                <template #icon>
                  <DeleteOutlined />
                </template>
                删除所选
              </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon><SyncOutlined /></template>
              </a-button>
            </a-tooltip>
            <a-button
              v-permission="{ action: 'ak_add' }"
              type="primary"
              style="margin-left: 12px"
              @click="addNewData"
            >
              <template #icon><PlusOutlined /></template> 新增凭证
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record._id"
      :dataSource="dataList.data"
      :loading="loading"
      :pagination="pagination"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
      <template #status="{ text: record }">
        <a-tag v-if="record == 1" color="green">启用</a-tag>
        <a-tag v-if="record == 0" color="red">关闭</a-tag>
      </template>
      <template #action="{ text: record }">
        <a v-permission="{ action: 'ak_add' }" @click="ak_edit(record)"><EditOutlined /> 编辑</a>
        <a-divider v-permission="{ action: 'ak_copy' }" type="vertical" />
        <a v-permission="{ action: 'ak_copy' }" @click="ak_copy(record)"><CopyOutlined /> 复用</a>
        <a-divider v-permission="{ action: 'ak_del' }" type="vertical" />
        <a v-permission="{ action: 'ak_del' }" style="color: red" @click="ak_delete(record)"
          ><DeleteOutlined /> 删除</a
        >
      </template>
    </a-table>
    <a-drawer
      width="50%"
      :title="drawerTitle"
      placement="right"
      :open="drawerShow"
      @close="
        () => {
          drawerShow = false
        }
      "
    >
      <template #extra>
        <a-button
          style="margin-right: 8px"
          @click="
            () => {
              drawerShow = false
            }
          "
          >取消</a-button
        >
        <a-button type="primary" @click="addServer">提交</a-button>
      </template>
      <a-form
        ref="formRef"
        :model="FormState"
        :rules="FormRule"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-tabs v-model:activeKey="activeKey" type="card">
          <a-tab-pane key="tab1" tab="凭证设置">
            <a-form-item label="标题" has-feedback required name="title">
              <a-input v-model:value="FormState.title" placeholder="请输入标题" />
            </a-form-item>
            <a-form-item label="凭证平台" has-feedback required name="platform">
              <a-radio-group v-model:value="FormState.platform" :options="pltformOption" />
            </a-form-item>
            <a-form-item label="IP限制" has-feedback required name="is_ip_limit">
              <a-radio-group v-model:value="FormState.is_ip_limit">
                <a-radio :key="1" :value="1">启用</a-radio>
                <a-radio :key="0" :value="0">关闭</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item
              v-if="FormState.is_ip_limit == 1"
              label="IP地址"
              has-feedback
              name="limit_server_ip"
            >
              <a-select
                v-model:value="FormState.limit_server_ip"
                mode="tags"
                style="width: 100%"
                :token-separators="[',']"
                placeholder="请输入可通过接口查询凭证的IP，多个以,分割"
              />
            </a-form-item>
            <a-form-item label="配置状态" has-feedback required name="status">
              <a-radio-group v-model:value="FormState.status">
                <a-radio :key="1" :value="1">启用</a-radio>
                <a-radio :key="0" :value="0">关闭</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane v-if="FormState.platform == 'aliyun'" key="tab2" tab="阿里云凭证设置">
            <a-form-item label="AccessKeyId" name="aliyun_key_id">
              <a-input v-model:value="FormState.aliyun_key_id" placeholder="请填写密钥ID">
                <template #suffix>
                  <a href="https://ram.console.aliyun.com/manage/ak" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="AccessKeySecret" name="aliyun_key_secret">
              <a-input
                v-model:value="FormState.aliyun_key_secret"
                placeholder="请填写访问密钥"
                :rows="2"
              >
                <template #suffix>
                  <a href="https://ram.console.aliyun.com/manage/ak" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane v-if="FormState.platform == 'tencent'" key="tab3" tab="腾讯云凭证设置">
            <a-form-item label="腾讯云SecretId" name="tenc_secret_id">
              <a-input v-model:value="FormState.tenc_secret_id" placeholder="请填写密钥ID">
                <template #suffix>
                  <a href="https://console.cloud.tencent.com/cam/capi" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="腾讯云SecretKey" name="tenc_secret_key">
              <a-input
                v-model:value="FormState.tenc_secret_key"
                placeholder="请填写访问密钥"
                :rows="2"
              >
                <template #suffix>
                  <a href="https://console.cloud.tencent.com/cam/capi" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane v-if="FormState.platform == 'huawei'" key="tab4" tab="华为云凭证设置">
            <a-form-item label="Application Key" name="huawei_app_key">
              <a-input v-model:value="FormState.huawei_app_key" placeholder="请填写Application Key">
                <template #suffix>
                  <a
                    href="https://console.huaweicloud.com/msgsms/?region=cn-north-4#/msgsms/applicationManage"
                    target="_blank"
                  >
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="Application Secret" name="huawei_app_secret">
              <a-input
                v-model:value="FormState.huawei_app_secret"
                placeholder="请填写Application Secret"
              >
                <template #suffix>
                  <a
                    href="https://console.huaweicloud.com/msgsms/?region=cn-north-4#/msgsms/applicationManage"
                    target="_blank"
                  >
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane v-if="FormState.platform == 'qiniu'" key="tab4" tab="七牛云凭证设置">
            <a-form-item label="AK" name="qiniu_ak">
              <a-input v-model:value="FormState.qiniu_ak" placeholder="请填写七牛云AK">
                <template #suffix>
                  <a href="https://portal.qiniu.com/user/key" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="SK" name="qiniu_sk">
              <a-input v-model:value="FormState.qiniu_sk" placeholder="请填写七牛云SK">
                <template #suffix>
                  <a href="https://portal.qiniu.com/user/key" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane v-if="FormState.platform == 'jdcloud'" key="ta5" tab="京东云凭证设置">
            <a-form-item label="Access Key ID">
              <a-input v-model:value="FormState.jdcloud_access_key_id" placeholder="请填写">
                <template #suffix>
                  <a href="https://uc.jdcloud.com/account/accesskey" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="Access Key Secret">
              <a-input v-model:value="FormState.jdcloud_access_key_secret" placeholder="请填写">
                <template #suffix>
                  <a href="https://uc.jdcloud.com/account/accesskey" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane v-if="FormState.platform == 'geetest'" key="ta6" tab="极验凭证设置">
            <a-form-item label="验证 ID">
              <a-input v-model:value="FormState.geetest_id" placeholder="请填写">
                <template #suffix>
                  <a href="https://console.geetest.com/sensbot/management" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="验证 Key">
              <a-input v-model:value="FormState.geetest_key" placeholder="请填写">
                <template #suffix>
                  <a href="https://console.geetest.com/sensbot/management" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane v-if="FormState.platform == 'smsbao'" key="ta6" tab="短信宝凭证设置">
            <a-form-item label="用户名">
              <a-input v-model:value="FormState.smsbao_username" placeholder="请填写">
                <template #suffix>
                  <a href="http://console.smsbao.com/#/account/infomation" target="_blank">
                    <a-tooltip title="在短信宝平台注册的用户名">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="登录密码/ApiKey">
              <a-input v-model:value="FormState.smsbao_password" placeholder="请填写">
                <template #suffix>
                  <a href="http://console.smsbao.com/#/isms/overview" target="_blank">
                    <a-tooltip
                      title="平台登录密码MD5后的值(32位，不区分大小写)或者ApiKey(推荐使用更安全)可在短信宝后台或联系客服获得"
                    >
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-drawer>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, ref } from 'vue'
import {
  Row,
  Col,
  Modal,
  Divider,
  Image,
  Drawer,
  Switch,
  InputPassword,
  InputNumber,
  Tabs,
  TabPane
} from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownOutlined,
  CopyOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons-vue'
import { delServerItem, delServerBatch, getServerList, editServerInfo } from '@/api/ak'
import { useRouter } from 'vue-router'
import { requestFailed, requestSuccess } from '@/utils/feedback'

export default defineComponent({
  name: 'AdsList',
  components: {
    SyncOutlined,
    PlusOutlined,
    DownOutlined,
    CopyOutlined,
    EditOutlined,
    QuestionCircleOutlined,
    DeleteOutlined,
    [Tabs.name]: Tabs,
    [TabPane.name]: TabPane,
    [Modal.name]: Modal,
    [Row.name]: Row,
    [Drawer.name]: Drawer,
    [Switch.name]: Switch,
    [InputPassword.name]: InputPassword,
    [InputNumber.name]: InputNumber,
    [Col.name]: Col,
    [Image.name]: Image,
    [Divider.name]: Divider
  },
  setup() {
    const formRef = ref()
    const router = useRouter()
    const state = reactive<any>({
      loading: true,
      drawerShow: false,
      drawerTitle: '凭证配置详情',
      activeKey: 'tab1',
      pltformOption: [
        {
          label: '阿里云',
          value: 'aliyun'
        },
        {
          label: '腾讯云',
          value: 'tencent'
        },
        {
          label: '华为云',
          value: 'huawei'
        },
        {
          label: '七牛云',
          value: 'qiniu'
        },
        {
          label: '京东云',
          value: 'jdcloud'
        },
        {
          label: '极验',
          value: 'geetest'
        },
        {
          label: '短信宝',
          value: 'smsbao'
        }
      ],
      dataList: [],
      selectedRowKeys: [],
      selectedKeysPage: {},
      listQuery: {
        pageNo: 1,
        pageSize: 15,
        title: '',
        platform: ''
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      pagination: {
        pageSizeOptions: ['15', '30', '50'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15,
        current: 1
      },
      columns: [
        {
          title: 'ID',
          dataIndex: '_id'
        },
        {
          title: '标题',
          dataIndex: 'title'
        },
        {
          title: '平台',
          dataIndex: 'platform_title'
        },
        {
          title: '配置状态',
          dataIndex: 'status',
          slots: { customRender: 'status' }
        },
        {
          title: '添加时间',
          dataIndex: 'create_time'
        },
        {
          title: '操作',
          width: '220px',
          slots: { customRender: 'action' }
        }
      ]
    })
    onMounted(() => {
      getDataList()
    })

    function handleTableChange(e) {
      state.loading = true
      state.pagination.pageSize = e.pageSize
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      state.pagination.current = e.current
      getDataList()
    }
    const FormState = reactive<any>({
      _id: '',
      title: '',
      is_ip_limit: 0,
      limit_server_ip: null,
      platform: '',
      status: 1
    })
    const FormRule = {
      title: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
      is_ip_limit: [
        { required: true, message: '请选择是否启用IP限制', trigger: ['blur', 'change'] }
      ],
      status: [{ required: true, message: '请选择配置状态', trigger: ['blur', 'change'] }],
      platform: [{ required: true, message: '请选择凭证平台', trigger: ['blur', 'change'] }]
    }

    function reloadList() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }

    function searchSubmit() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }
    function ak_copy(itemData) {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerTitle = '复制凭证配置'
      for (let item in itemData) {
        if (item != '_id') {
          let copyTips = item == 'title' ? ' - 复制' : ''
          FormState[item] = itemData[item] + copyTips
        }
      }
      state.drawerShow = true
    }

    function getDataList() {
      getServerList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }
    function ak_edit(res) {
      state.drawerTitle = '编辑凭证配置'
      for (let item in FormState) {
        FormState[item] = ''
      }
      for (let item in res) {
        FormState[item] = res[item]
      }
      state.drawerShow = true
    }
    function addNewData() {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerTitle = '新增凭证配置'
      state.drawerShow = true
    }
    function ak_delete(data) {
      Modal.confirm({
        title: '确认永久删除此凭证?',
        content: '【' + data._id + '】',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delServerItem({ id: data._id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              getDataList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    const addServer = () => {
      formRef.value
        .validate()
        .then(() => {
          editServerInfo(FormState).then((res) => {
            if (res.code === 200) {
              requestSuccess(res)
              formRef.value.resetFields()
              state.loading = true
              state.drawerShow = false
              reloadList()
            } else {
              requestFailed(res)
            }
          })
        })
        .catch(() => {
          return false
        })
    }
    function deleteSelect() {
      Modal.confirm({
        title: '确认批量删除所选内容?',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delServerBatch({ ids: state.selectedRowKeys })
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                getDataList()
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    const onSelectChange = (selectedRowKeys) => {
      state.selectedKeysPage[state.listQuery.pageNo] = selectedRowKeys
      let nowList: any[] = []
      for (const key in state.selectedKeysPage) {
        nowList = nowList.concat(state.selectedKeysPage[key])
      }
      const uniqueList = [...new Set(nowList)]
      state.selectedRowKeys = uniqueList
    }
    return {
      ...toRefs(state),
      handleTableChange,
      deleteSelect,
      onSelectChange,
      reloadList,
      searchSubmit,
      ak_delete,
      formRef,
      addServer,
      FormState,
      FormRule,
      addNewData,
      router,
      ak_edit,
      ak_copy,
      getDataList
    }
  }
})
</script>

<style scoped></style>
